//
//  HttpClientManager.m
//  xqt
//
//  Created by Senela on 14-12-18.
//  Copyright (c) 2014年 myqu. All rights reserved.
//

#import "HttpClientManager.h"
#import "UIImageView+AFNetworking.h"
#import "SVProgressHUD.h"
#import "JSONKit.h"
#import "AppDelegate.h"
#import "AppMacro.h"
#import "DataModel.h"

static NSString * const AFAppDotNetAPIBaseURLString = @"";

@implementation HttpClientManager

+ (instancetype)sharedClient
{
    static HttpClientManager *_sharedClient = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _sharedClient = [[HttpClientManager alloc] initWithBaseURL:[NSURL URLWithString:AFAppDotNetAPIBaseURLString]];
        // 设置超时时间
        _sharedClient.requestSerializer.timeoutInterval = 30;
        
        _sharedClient.securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
    });
    
    return _sharedClient;
}


#pragma  mark ----- private
-(void)getName:(NSString *)requestName  url:(NSString *)url parameter:(NSDictionary *)parameter success:(ResponseBlock)success
        failure:(ResponseBlock)failure
{
    
    NSMutableString *requestUrl = [[NSMutableString alloc] initWithString:[NSString stringWithFormat:@"%@%@", BASEURL, url]];
    int index = 0;
    for(NSString *key in parameter.allKeys){
        
        NSString *param = [NSString stringWithFormat:@"%@=%@", key, parameter[key]];
        if(index == 0){
            
            [requestUrl appendString:param];
        }else{
            
            [requestUrl appendString:[NSString stringWithFormat:@"&%@", param]];
        }
        index++;
    }
    NSLog(@"Request Url \n : URL %@", [NSString stringWithString:requestUrl]);
    
    [SVProgressHUD setForegroundColor:[UIColor colorWithRed:0 green:0 blue:0 alpha:0.5]];
    [SVProgressHUD setBackgroundColor:[UIColor whiteColor]];
    [self GET:[NSMutableString stringWithFormat:@"%@%@?", BASEURL, url] parameters:parameter success:^(NSURLSessionDataTask *task, id responseObject)
     {
         
         NSLog(@"%@--- SuccessBlock:%@",requestName, responseObject);
         
         NSNumber *result = [responseObject objectForKey:@"success"];
         if(result.intValue == 1 && success){
             JsonRetMsg *msg = [[JsonRetMsg alloc] init];
             msg.error = [responseObject objectForKey:@"error"];
             msg.success = [responseObject objectForKey:@"success"];
             msg.data = [responseObject objectForKey:@"data"];
             success(msg);
         }
         else
         {
             JsonRetMsg *msg = [[JsonRetMsg alloc] init];
             msg.error = [responseObject objectForKey:@"error"];
             //            [SVProgressHUD showErrorWithStatus:msg.errorMsg];
             failure(msg);
         }
         
         
     } failure:^(NSURLSessionDataTask *task, NSError *error) {
         NSLog( @"%@--- FailedBlock:%@", requestName, error);
         
         if (failure)
         {
             JsonRetMsg *msg = [[JsonRetMsg alloc] init];
             
                         if(error.code == -1004)
                         {
//                             msg.errorMsg = @"网络连接断开，请稍后再试！";
//                             [SVProgressHUD showErrorWithStatus:msg.errorMsg];
                             [SVProgressHUD showErrorWithStatus:@"网络连接断开，请稍后再试！"];
                         }
                         else  if(error.code == -1001)
                         {
//                             msg.errorMsg = @"网络请求超时，请稍后再试！";
//                             [SVProgressHUD showErrorWithStatus:msg.errorMsg];
                             [SVProgressHUD showErrorWithStatus:@"网络请求超时，请稍后再试！"];
                         }
                         else{
             
//                             msg.errorMsg = @"亲，你的网络不给力，请检查网络！";
//                             [SVProgressHUD showErrorWithStatus:msg.errorMsg];
                             [SVProgressHUD showErrorWithStatus:@"亲，你的网络不给力，请检查网络！"];
                             NSLog(@"%@", error.description);
                         }
             
             failure(msg);
         }
     }];
}


-(void)postName:(NSString *)requestName  url:(NSString *)url parameter:(NSDictionary *)parameter success:(ResponseBlock)success
    failure:(ResponseBlock)failure
{
    
    NSMutableString *requestUrl = [[NSMutableString alloc] initWithString:url];
    int index = 0;
    for(NSString *key in parameter.allKeys){
        
        NSString *param = [NSString stringWithFormat:@"%@=%@", key, parameter[key]];
        if(index == 0){
            
            [requestUrl appendString:param];
        }else{
            
            [requestUrl appendString:[NSString stringWithFormat:@"&%@", param]];
        }
        index++;
    }
    NSLog(@"Request Url \n : URL %@", [NSString stringWithString:requestUrl]);
    
    [SVProgressHUD setForegroundColor:[UIColor whiteColor]];
    [SVProgressHUD setBackgroundColor:[UIColor colorWithRed:0 green:0 blue:0 alpha:0.5]];
    [self POST:url parameters:parameter success:^(NSURLSessionDataTask *task, id responseObject)
    {
    
        NSLog(@"%@--- SuccessBlock:%@",requestName, responseObject);
        
        NSNumber *result = [responseObject objectForKey:@"result"];
        if(result.intValue == 1 && success){
            JsonRetMsg *msg = [[JsonRetMsg alloc] init];
            msg.error = [responseObject objectForKey:@"error"];
            msg.success = [responseObject objectForKey:@"success"];
            msg.data = [responseObject objectForKey:@"object"];
            success(msg);
        }
        else
        {
            JsonRetMsg *msg = [[JsonRetMsg alloc] init];
            msg.error = [responseObject objectForKey:@"error"];
//            [SVProgressHUD showErrorWithStatus:msg.errorMsg];
            failure(msg);
        }

        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog( @"%@--- FailedBlock:%@", requestName, error);
        
        if (failure)
        {
            JsonRetMsg *msg = [[JsonRetMsg alloc] init];
            
//            if(error.code == -1004)
//            {
//                msg.errorMsg = @"网络连接断开，请稍后再试！";
//                [SVProgressHUD showErrorWithStatus:msg.errorMsg];
//            }
//            else  if(error.code == -1001)
//            {
//                msg.errorMsg = @"网络请求超时，请稍后再试！";
//                [SVProgressHUD showErrorWithStatus:msg.errorMsg];
//            }
//            else{
//                
//                msg.errorMsg = @"亲，你的网络不给力，请检查网络！";
//                [SVProgressHUD showErrorWithStatus:msg.errorMsg];
//                NSLog(@"%@", error.description);
//            }
            
            failure(msg);
        }
    }];
}


-(void)requestImageInfoWithUrl:(NSString *)url imgView:(UIImageView *)imgView
{
    __weak UIImageView *weakImgView = imgView;
    [weakImgView setImageWithURLRequest:[[NSURLRequest alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@", url]]]
     
                       placeholderImage:nil
                                success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image){
                                    weakImgView.image = image;
                                }
                                failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error){
                                    
                                }];
}

-(void)requestImageInfoWithUrl:(NSString *)url imgView:(UIImageView *)imgView placeholderImage:(NSString*)placeImgStr
{
    __weak UIImageView *weakImgView = imgView;
    [weakImgView setImageWithURLRequest:[[NSURLRequest alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@", url]]]
                       placeholderImage: [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:placeImgStr ofType:@"png"]]
                                success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image)
    {
                                    weakImgView.image = image;
                                }
                                failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error)
    {
                                    
                                }];
}

-(UIImage *)loadImgeWithName:(NSString *)imgStr
{
    UIImage *img = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:imgStr ofType:@"png"]];
    return img;
}

#pragma  mark ----- public
#pragma mark ------  用户登录
- (void)loginRequestWithMobilePhone:(NSString *)mobilephone
                             WithAuthCode:(NSString *)authcode
                          WithSucessBlock:(ResponseBlock )sucessBlock
                          withFailedBlock:(ResponseErrorBlock )failedBlock{
    
    NSDictionary *parameters = [[NSMutableDictionary alloc] init];
    [parameters setValue:mobilephone forKey:@"mobilephone"];
    [parameters setValue:authcode forKey:@"authcode"];
    
    [self getName:@"用户登录" url:@"login" parameter:parameters success:sucessBlock failure:failedBlock];
}

#pragma mark ------  添加车牌
- (void)addCarRequestWithMobilePhone:(NSString *)mobilephone
                        WithUserId:(NSString *)userid
                    WithProvincename:(NSString *)provincename
                 Withcarnumbersuffix:(NSString *)carnumbersuffix
                       WithIsprimary:(NSString *)isprimary
                    WithSucessBlock:(ResponseBlock )sucessBlock
                    withFailedBlock:(ResponseErrorBlock )failedBlock{
    
    NSDictionary *parameters = [[NSMutableDictionary alloc] init];
    [parameters setValue:mobilephone forKey:@"mobilephone"];
    [parameters setValue:userid forKey:@"userid"];
    [parameters setValue:provincename forKey:@"provincename"];
    [parameters setValue:carnumbersuffix forKey:@"carnumbersuffix"];
    [parameters setValue:isprimary forKey:@"isprimary"];
    
    [self getName:@"添加车牌" url:@"car/addcar" parameter:parameters success:sucessBlock failure:failedBlock];
}

#pragma mark ------ 首页地图搜索
- (void)mapParkingSearchRequestWithCityNo:(NSString *)cityno
                               WithUserId:(NSString *)userid
                               Withgpslat:(NSString *)gpslat
                               Withgpslon:(NSString *)gpslon
                          WithSucessBlock:(ResponseBlock )sucessBlock
                          withFailedBlock:(ResponseErrorBlock )failedBlock{
    
    NSDictionary *parameters = [[NSMutableDictionary alloc] init];
    [parameters setValue:cityno forKey:@"cityno"];
    [parameters setValue:userid forKey:@"userid"];
    [parameters setValue:gpslat forKey:@"gpslat"];
    [parameters setValue:gpslon forKey:@"gpslon"];
    
    [self getName:@"首页地图搜索" url:@"/parking/indexsearch" parameter:parameters success:^(JsonRetMsg *response){
        
        NSMutableArray *resultArray = [[NSMutableArray alloc] init];
        NSArray *array = response.data;
        for(NSDictionary *dic in array){
            
            ParkingSearchModel *model = [[ParkingSearchModel alloc] initWithDictionary:dic error:nil];
            [resultArray addObject:model];
        }
        response.data = resultArray;
        sucessBlock(response);
    }failure:failedBlock];
}

#pragma mark ------  获取停车场信息
- (void)ParkingPortDetailRequestWithParkingId:(NSString *)parkingid
                          WithUserId:(NSString *)userid
                     WithSucessBlock:(ResponseBlock )sucessBlock
                     withFailedBlock:(ResponseErrorBlock )failedBlock{
    
    NSDictionary *parameters = [[NSMutableDictionary alloc] init];
    [parameters setValue:userid forKey:@"userid"];
    [parameters setValue:parkingid forKey:@"parkingid"];
    
    [self getName:@"获取停车场信息" url:@"/order/prebooking" parameter:parameters success:sucessBlock failure:failedBlock];
}

#pragma mark ------  预约支付
- (void)payBookParkingSpaceRequestWithParkingId:(NSString *)parkingid
                                     WithUserId:(NSString *)userid
              WithFirstpreBookingParkingSpaceNo:(NSString *)firstpreBookingParkingSpaceNo
                WithFirstpreBookingParkingCarNo:(NSString *)firstpreBookingParkingCarNo
             WithSecondpreBookingParkingSpaceNo:(NSString *)secondpreBookingParkingSpaceNo
               WithSecondpreBookingParkingCarNo:(NSString *)secondpreBookingParkingCarNo
                                WithSucessBlock:(ResponseBlock )sucessBlock
                                withFailedBlock:(ResponseErrorBlock )failedBlock{
    
    NSDictionary *parameters = [[NSMutableDictionary alloc] init];
    [parameters setValue:userid forKey:@"userid"];
    [parameters setValue:parkingid forKey:@"parkingid"];
    if(firstpreBookingParkingSpaceNo != nil && firstpreBookingParkingSpaceNo.length != 0){
        
        [parameters setValue:firstpreBookingParkingSpaceNo forKey:@"preBookingParkingSpaceList[0].parkingspaceno"];
        [parameters setValue:firstpreBookingParkingCarNo forKey:@"preBookingParkingSpaceList[0].carnumber"];
    }
    if(secondpreBookingParkingSpaceNo != nil && secondpreBookingParkingSpaceNo.length != 0){
        
        [parameters setValue:secondpreBookingParkingSpaceNo forKey:@"preBookingParkingSpaceList[1].parkingspaceno"];
        [parameters setValue:secondpreBookingParkingCarNo forKey:@"preBookingParkingSpaceList[1].carnumber"];
    }
    
    [self getName:@"预约支付" url:@"order/submitprebooking" parameter:parameters success:sucessBlock failure:failedBlock];
}

#pragma mark ------ 查询我的预约订单
- (void)myBookOrdersRequestWithMobilephone:(NSString *)mobilephone
                               WithUserId:(NSString *)userid
                          WithSucessBlock:(ResponseBlock )sucessBlock
                          withFailedBlock:(ResponseErrorBlock )failedBlock{
    
    NSDictionary *parameters = [[NSMutableDictionary alloc] init];
    [parameters setValue:mobilephone forKey:@"mobilephone"];
    [parameters setValue:userid forKey:@"userid"];
    
    [self getName:@"查询我的预约订单" url:@"order/listorder" parameter:parameters success:^(JsonRetMsg *response){
        
        NSMutableArray *resultArray = [[NSMutableArray alloc] init];
        NSArray *array = response.data;
        for(NSDictionary *dic in array){
            
            BookParkingPortOrderModel *model = [[BookParkingPortOrderModel alloc] initWithDictionary:dic error:nil];
            [resultArray addObject:model];
        }
        response.data = resultArray;
        sucessBlock(response);
    }failure:failedBlock];
}

#pragma mark ------ 查询预约订单详情
- (void)orderDetailRequestWithOrderno:(NSString *)orderno
                           WithUserId:(NSString *)userid
                        WithOrdertype:(NSString *)ordertype
                           WithSucessBlock:(ResponseBlock )sucessBlock
                           withFailedBlock:(ResponseErrorBlock )failedBlock{
    
    NSDictionary *parameters = [[NSMutableDictionary alloc] init];
    [parameters setValue:orderno forKey:@"orderno"];
    [parameters setValue:userid forKey:@"userid"];
    [parameters setValue:ordertype forKey:@"ordertype"];
    
    [self getName:@"查询预约订单详情" url:@"order/bookingorderdetail" parameter:parameters success:sucessBlock failure:failedBlock];
}

#pragma mark ------ 查询我的车牌列表
- (void)myCarsListRequestWithUserId:(NSString *)userid
                           WithSucessBlock:(ResponseBlock )sucessBlock
                           withFailedBlock:(ResponseErrorBlock )failedBlock{
    
    NSDictionary *parameters = [[NSMutableDictionary alloc] init];
    [parameters setValue:userid forKey:@"userid"];
    
    [self getName:@"查询我的车牌列表" url:@"car/listcar" parameter:parameters success:^(JsonRetMsg *response){
        
        NSMutableArray *resultArray = [[NSMutableArray alloc] init];
        NSArray *array = response.data;
        for(NSDictionary *dic in array){
            
            MyCarListModel *model = [[MyCarListModel alloc] initWithDictionary:dic error:nil];
            [resultArray addObject:model];
        }
        response.data = resultArray;
        sucessBlock(response);
    }failure:failedBlock];
}

#pragma mark ------ 取消预约订单
- (void)cancelBookOrderRequestWithOrderno:(NSString *)orderno
                           WithUserId:(NSString *)userid
                        WithMobilePhone:(NSString *)mobilephone
                      WithSucessBlock:(ResponseBlock )sucessBlock
                      withFailedBlock:(ResponseErrorBlock )failedBlock{
    
    NSDictionary *parameters = [[NSMutableDictionary alloc] init];
    [parameters setValue:orderno forKey:@"orderno"];
    [parameters setValue:userid forKey:@"userid"];
    [parameters setValue:mobilephone forKey:@"mobilephone"];
    
    [self getName:@"取消预约订单" url:@"order/bookingordercancel" parameter:parameters success:sucessBlock failure:failedBlock];
}

#pragma mark ------ 支付预约订单
- (void)payBookOrderRequestWithOrderno:(NSString *)orderno
                               WithUserId:(NSString *)userid
                          WithMobilePhone:(NSString *)mobilephone
                          WithSucessBlock:(ResponseBlock )sucessBlock
                          withFailedBlock:(ResponseErrorBlock )failedBlock{
    
    NSDictionary *parameters = [[NSMutableDictionary alloc] init];
    [parameters setValue:orderno forKey:@"orderno"];
    [parameters setValue:userid forKey:@"userid"];
    [parameters setValue:mobilephone forKey:@"mobilephone"];
    
    [self getName:@"支付预约订单" url:@"order/bookingorderpay" parameter:parameters success:sucessBlock failure:failedBlock];
}

@end
